# SPDX-License-Identifier: GPL-2.0
# Backward compatibility
asflags-y  += $(EXTRA_AFLAGS)
ccflags-y  += $(EXTRA_CFLAGS)
cppflags-y += $(EXTRA_CPPFLAGS)
ldflags-y  += $(EXTRA_LDFLAGS)

# flags that take effect in current and sub directories
KBUILD_AFLAGS += $(subdir-asflags-y)
KBUILD_CFLAGS += $(subdir-ccflags-y)

# Figure out what we need to build from the various variables
# ===========================================================================

# When an object is listed to be built compiled-in and modular,
# only build the compiled-in version
obj-m := $(filter-out $(obj-y),$(obj-m))

# Libraries are always collected in one lib file.
# Filter out objects already built-in
lib-y := $(filter-out $(obj-y), $(sort $(lib-y) $(lib-m)))

# Determine modorder.
# Unfortunately, we don't have information about ordering between -y
# and -m subdirs.  Just put -y's first.
modorder	:= $(patsubst %/,%/modules.order, $(filter %/, $(obj-y)) $(obj-m:.o=.ko))

# Handle objects in subdirs
# ---------------------------------------------------------------------------
# o if we encounter foo/ in $(obj-y), replace it by foo/built-in.a
#   and add the directory to the list of dirs to descend into: $(subdir-y)
# o if we encounter foo/ in $(obj-m), remove it from $(obj-m)
#   and add the directory to the list of dirs to descend into: $(subdir-m)
__subdir-y	:= $(patsubst %/,%,$(filter %/, $(obj-y)))
subdir-y	+= $(__subdir-y)
__subdir-m	:= $(patsubst %/,%,$(filter %/, $(obj-m)))
subdir-m	+= $(__subdir-m)
obj-y		:= $(patsubst %/, %/built-in.a, $(obj-y))
obj-m		:= $(filter-out %/, $(obj-m))

# Subdirectories we need to descend into
subdir-ym	:= $(sort $(subdir-y) $(subdir-m))

# if $(foo-objs), $(foo-y), or $(foo-m) exists, foo.o is a composite object
multi-used-y := $(sort $(foreach m,$(obj-y), $(if $(strip $($(m:.o=-objs)) $($(m:.o=-y))), $(m))))
multi-used-m := $(sort $(foreach m,$(obj-m), $(if $(strip $($(m:.o=-objs)) $($(m:.o=-y)) $($(m:.o=-m))), $(m))))
multi-used   := $(multi-used-y) $(multi-used-m)
single-used-m := $(sort $(filter-out $(multi-used-m),$(obj-m)))

# $(subdir-obj-y) is the list of objects in $(obj-y) which uses dir/ to
# tell kbuild to descend
subdir-obj-y := $(filter %/built-in.a, $(obj-y))

# Replace multi-part objects by their individual parts,
# including built-in.a from subdirectories
real-obj-y := $(foreach m, $(obj-y), $(if $(strip $($(m:.o=-objs)) $($(m:.o=-y))),$($(m:.o=-objs)) $($(m:.o=-y)),$(m)))
real-obj-m := $(foreach m, $(obj-m), $(if $(strip $($(m:.o=-objs)) $($(m:.o=-y)) $($(m:.o=-m))),$($(m:.o=-objs)) $($(m:.o=-y)) $($(m:.o=-m)),$(m)))

# DTB
# If CONFIG_OF_ALL_DTBS is enabled, all DT blobs are built
extra-y				+= $(dtb-y)
extra-$(CONFIG_OF_ALL_DTBS)	+= $(dtb-)

# Add subdir path

extra-y		:= $(addprefix $(obj)/,$(extra-y))
always		:= $(addprefix $(obj)/,$(always))
targets		:= $(addprefix $(obj)/,$(targets))
modorder	:= $(addprefix $(obj)/,$(modorder))
obj-m		:= $(addprefix $(obj)/,$(obj-m))
lib-y		:= $(addprefix $(obj)/,$(lib-y))
subdir-obj-y	:= $(addprefix $(obj)/,$(subdir-obj-y))
real-obj-y	:= $(addprefix $(obj)/,$(real-obj-y))
real-obj-m	:= $(addprefix $(obj)/,$(real-obj-m))
single-used-m	:= $(addprefix $(obj)/,$(single-used-m))
multi-used-m	:= $(addprefix $(obj)/,$(multi-used-m))
subdir-ym	:= $(addprefix $(obj)/,$(subdir-ym))

# Finds the multi-part object the current object will be linked into.
# If the object belongs to two or more multi-part objects, all of them are
# concatenated with a colon separator.
modname-multi = $(subst $(space),:,$(sort $(foreach m,$(multi-used),\
		$(if $(filter $*.o, $($(m:.o=-objs)) $($(m:.o=-y)) $($(m:.o=-m))),$(m:.o=)))))

modname = $(if $(modname-multi),$(modname-multi),$(basetarget))

# These flags are needed for modversions and compiling, so we define them here
# $(modname_flags) defines KBUILD_MODNAME as the name of the module it will
# end up in (or would, if it gets compiled in)
name-fix = $(squote)$(quote)$(subst $(comma),_,$(subst -,_,$1))$(quote)$(squote)
basename_flags = -DKBUILD_BASENAME=$(call name-fix,$(basetarget))
modname_flags  = -DKBUILD_MODNAME=$(call name-fix,$(modname))

orig_c_flags   = $(KBUILD_CPPFLAGS) $(KBUILD_CFLAGS) \
                 $(ccflags-y) $(CFLAGS_$(basetarget).o)
_c_flags       = $(filter-out $(CFLAGS_REMOVE_$(basetarget).o), $(orig_c_flags))
orig_a_flags   = $(KBUILD_CPPFLAGS) $(KBUILD_AFLAGS) \
                 $(asflags-y) $(AFLAGS_$(basetarget).o)
_a_flags       = $(filter-out $(AFLAGS_REMOVE_$(basetarget).o), $(orig_a_flags))
_cpp_flags     = $(KBUILD_CPPFLAGS) $(cppflags-y) $(CPPFLAGS_$(@F))

#
# Enable gcov profiling flags for a file, directory or for all files depending
# on variables GCOV_PROFILE_obj.o, GCOV_PROFILE and CONFIG_GCOV_PROFILE_ALL
# (in this order)
#
ifeq ($(CONFIG_GCOV_KERNEL),y)
_c_flags += $(if $(patsubst n%,, \
		$(GCOV_PROFILE_$(basetarget).o)$(GCOV_PROFILE)$(CONFIG_GCOV_PROFILE_ALL)), \
		$(CFLAGS_GCOV))
endif

#
# Enable address sanitizer flags for kernel except some files or directories
# we don't want to check (depends on variables KASAN_SANITIZE_obj.o, KASAN_SANITIZE)
#
ifeq ($(CONFIG_KASAN),y)
_c_flags += $(if $(patsubst n%,, \
		$(KASAN_SANITIZE_$(basetarget).o)$(KASAN_SANITIZE)y), \
		$(CFLAGS_KASAN), $(CFLAGS_KASAN_NOSANITIZE))
endif

ifeq ($(CONFIG_UBSAN),y)
_c_flags += $(if $(patsubst n%,, \
		$(UBSAN_SANITIZE_$(basetarget).o)$(UBSAN_SANITIZE)$(CONFIG_UBSAN_SANITIZE_ALL)), \
		$(CFLAGS_UBSAN))
endif

ifeq ($(CONFIG_KCOV),y)
_c_flags += $(if $(patsubst n%,, \
	$(KCOV_INSTRUMENT_$(basetarget).o)$(KCOV_INSTRUMENT)$(CONFIG_KCOV_INSTRUMENT_ALL)), \
	$(CFLAGS_KCOV))
endif

# If building the kernel in a separate objtree expand all occurrences
# of -Idir to -I$(srctree)/dir except for absolute paths (starting with '/').

ifeq ($(KBUILD_SRC),)
__c_flags	= $(_c_flags)
__a_flags	= $(_a_flags)
__cpp_flags     = $(_cpp_flags)
else

# -I$(obj) locates generated .h files
# $(call addtree,-I$(obj)) locates .h files in srctree, from generated .c files
#   and locates generated .h files
# FIXME: Replace both with specific CFLAGS* statements in the makefiles
__c_flags	= $(if $(obj),$(call addtree,-I$(src)) -I$(obj)) \
		  $(call flags,_c_flags)
__a_flags	= $(call flags,_a_flags)
__cpp_flags     = $(call flags,_cpp_flags)
endif

c_flags        = -Wp,-MD,$(depfile) $(NOSTDINC_FLAGS) $(LINUXINCLUDE)     \
		 -include $(srctree)/include/linux/compiler_types.h       \
		 $(__c_flags) $(modkern_cflags)                           \
		 $(basename_flags) $(modname_flags)

a_flags        = -Wp,-MD,$(depfile) $(NOSTDINC_FLAGS) $(LINUXINCLUDE)     \
		 $(__a_flags) $(modkern_aflags)

cpp_flags      = -Wp,-MD,$(depfile) $(NOSTDINC_FLAGS) $(LINUXINCLUDE)     \
		 $(__cpp_flags)

ld_flags       = $(KBUILD_LDFLAGS) $(ldflags-y) $(LDFLAGS_$(@F))

DTC_INCLUDE    := $(srctree)/scripts/dtc/include-prefixes

dtc_cpp_flags  = -Wp,-MD,$(depfile).pre.tmp -nostdinc                    \
		 $(addprefix -I,$(DTC_INCLUDE))                          \
		 -undef -D__DTS__

# Useful for describing the dependency of composite objects
# Usage:
#   $(call multi_depend, multi_used_targets, suffix_to_remove, suffix_to_add)
define multi_depend
$(foreach m, $(notdir $1), \
	$(eval $(obj)/$m: \
	$(addprefix $(obj)/, $(foreach s, $3, $($(m:%$(strip $2)=%$(s)))))))
endef

# LEX
# ---------------------------------------------------------------------------
quiet_cmd_flex = LEX     $@
      cmd_flex = $(LEX) -o$@ -L $<

$(obj)/%.lex.c: $(src)/%.l FORCE
	$(call if_changed,flex)

# YACC
# ---------------------------------------------------------------------------
quiet_cmd_bison = YACC    $@
      cmd_bison = $(YACC) -o$@ -t -l $<

$(obj)/%.tab.c: $(src)/%.y FORCE
	$(call if_changed,bison)

quiet_cmd_bison_h = YACC    $@
      cmd_bison_h = $(YACC) -o/dev/null --defines=$@ -t -l $<

$(obj)/%.tab.h: $(src)/%.y FORCE
	$(call if_changed,bison_h)

# Shipped files
# ===========================================================================

quiet_cmd_shipped = SHIPPED $@
cmd_shipped = cat $< > $@

$(obj)/%: $(src)/%_shipped
	$(call cmd,shipped)

# Commands useful for building a boot image
# ===========================================================================
#
#	Use as following:
#
#	target: source(s) FORCE
#		$(if_changed,ld/objcopy/gzip)
#
#	and add target to extra-y so that we know we have to
#	read in the saved command line

# Linking
# ---------------------------------------------------------------------------

quiet_cmd_ld = LD      $@
cmd_ld = $(LD) $(ld_flags) $(filter-out FORCE,$^) -o $@

# Objcopy
# ---------------------------------------------------------------------------

quiet_cmd_objcopy = OBJCOPY $@
cmd_objcopy = $(OBJCOPY) $(OBJCOPYFLAGS) $(OBJCOPYFLAGS_$(@F)) $< $@

# Gzip
# ---------------------------------------------------------------------------

quiet_cmd_gzip = GZIP    $@
cmd_gzip = (cat $(filter-out FORCE,$^) | gzip -n -f -9 > $@) || \
	(rm -f $@ ; false)

# DTC
# ---------------------------------------------------------------------------
DTC ?= $(objtree)/scripts/dtc/dtc

# Disable noisy checks by default
ifeq ($(findstring 1,$(KBUILD_ENABLE_EXTRA_GCC_CHECKS)),)
DTC_FLAGS += -Wno-unit_address_vs_reg \
	-Wno-unit_address_format \
	-Wno-avoid_unnecessary_addr_size \
	-Wno-alias_paths \
	-Wno-graph_child_address \
	-Wno-graph_port \
	-Wno-simple_bus_reg \
	-Wno-unique_unit_address \
	-Wno-pci_device_reg
endif

ifneq ($(findstring 2,$(KBUILD_ENABLE_EXTRA_GCC_CHECKS)),)
DTC_FLAGS += -Wnode_name_chars_strict \
	-Wproperty_name_chars_strict
endif

DTC_FLAGS += $(DTC_FLAGS_$(basetarget))

# Generate an assembly file to wrap the output of the device tree compiler
quiet_cmd_dt_S_dtb= DTB     $@
cmd_dt_S_dtb=						\
(							\
	echo '\#include <asm-generic/vmlinux.lds.h>'; 	\
	echo '.section .dtb.init.rodata,"a"';		\
	echo '.balign STRUCT_ALIGNMENT';		\
	echo '.global __dtb_$(subst -,_,$(*F))_begin';	\
	echo '__dtb_$(subst -,_,$(*F))_begin:';		\
	echo '.incbin "$<" ';				\
	echo '__dtb_$(subst -,_,$(*F))_end:';		\
	echo '.global __dtb_$(subst -,_,$(*F))_end';	\
	echo '.balign STRUCT_ALIGNMENT'; 		\
) > $@

$(obj)/%.dtb.S: $(obj)/%.dtb FORCE
	$(call if_changed,dt_S_dtb)

quiet_cmd_dtc = DTC     $@
cmd_dtc = mkdir -p $(dir ${dtc-tmp}) ; \
	$(CPP) $(dtc_cpp_flags) -x assembler-with-cpp -o $(dtc-tmp) $< ; \
	$(DTC) -O dtb -o $@ -b 0 \
		$(addprefix -i,$(dir $<) $(DTC_INCLUDE)) $(DTC_FLAGS) \
		-d $(depfile).dtc.tmp $(dtc-tmp) ; \
	cat $(depfile).pre.tmp $(depfile).dtc.tmp > $(depfile)

$(obj)/%.dtb: $(src)/%.dts $(DTC) FORCE
	$(call if_changed_dep,dtc)

dtc-tmp = $(subst $(comma),_,$(dot-target).dts.tmp)

# Bzip2
# ---------------------------------------------------------------------------

# Bzip2 and LZMA do not include size in file... so we have to fake that;
# append the size as a 32-bit littleendian number as gzip does.
size_append = printf $(shell						\
dec_size=0;								\
for F in $1; do								\
	fsize=$$($(CONFIG_SHELL) $(srctree)/scripts/file-size.sh $$F);	\
	dec_size=$$(expr $$dec_size + $$fsize);				\
done;									\
printf "%08x\n" $$dec_size |						\
	sed 's/\(..\)/\1 /g' | {					\
		read ch0 ch1 ch2 ch3;					\
		for ch in $$ch3 $$ch2 $$ch1 $$ch0; do			\
			printf '%s%03o' '\\' $$((0x$$ch)); 		\
		done;							\
	}								\
)

quiet_cmd_bzip2 = BZIP2   $@
cmd_bzip2 = (cat $(filter-out FORCE,$^) | \
	bzip2 -9 && $(call size_append, $(filter-out FORCE,$^))) > $@ || \
	(rm -f $@ ; false)

# Lzma
# ---------------------------------------------------------------------------

quiet_cmd_lzma = LZMA    $@
cmd_lzma = (cat $(filter-out FORCE,$^) | \
	lzma -9 && $(call size_append, $(filter-out FORCE,$^))) > $@ || \
	(rm -f $@ ; false)

quiet_cmd_lzo = LZO     $@
cmd_lzo = (cat $(filter-out FORCE,$^) | \
	lzop -9 && $(call size_append, $(filter-out FORCE,$^))) > $@ || \
	(rm -f $@ ; false)

quiet_cmd_lz4 = LZ4     $@
cmd_lz4 = (cat $(filter-out FORCE,$^) | \
	lz4c -l -c1 stdin stdout && $(call size_append, $(filter-out FORCE,$^))) > $@ || \
	(rm -f $@ ; false)

# U-Boot mkimage
# ---------------------------------------------------------------------------

MKIMAGE := $(srctree)/scripts/mkuboot.sh

# SRCARCH just happens to match slightly more than ARCH (on sparc), so reduces
# the number of overrides in arch makefiles
UIMAGE_ARCH ?= $(SRCARCH)
UIMAGE_COMPRESSION ?= $(if $(2),$(2),none)
UIMAGE_OPTS-y ?=
UIMAGE_TYPE ?= kernel
UIMAGE_LOADADDR ?= arch_must_set_this
UIMAGE_ENTRYADDR ?= $(UIMAGE_LOADADDR)
UIMAGE_NAME ?= 'Linux-$(KERNELRELEASE)'
UIMAGE_IN ?= $<
UIMAGE_OUT ?= $@

quiet_cmd_uimage = UIMAGE  $(UIMAGE_OUT)
      cmd_uimage = $(CONFIG_SHELL) $(MKIMAGE) -A $(UIMAGE_ARCH) -O linux \
			-C $(UIMAGE_COMPRESSION) $(UIMAGE_OPTS-y) \
			-T $(UIMAGE_TYPE) \
			-a $(UIMAGE_LOADADDR) -e $(UIMAGE_ENTRYADDR) \
			-n $(UIMAGE_NAME) -d $(UIMAGE_IN) $(UIMAGE_OUT)

# XZ
# ---------------------------------------------------------------------------
# Use xzkern to compress the kernel image and xzmisc to compress other things.
#
# xzkern uses a big LZMA2 dictionary since it doesn't increase memory usage
# of the kernel decompressor. A BCJ filter is used if it is available for
# the target architecture. xzkern also appends uncompressed size of the data
# using size_append. The .xz format has the size information available at
# the end of the file too, but it's in more complex format and it's good to
# avoid changing the part of the boot code that reads the uncompressed size.
# Note that the bytes added by size_append will make the xz tool think that
# the file is corrupt. This is expected.
#
# xzmisc doesn't use size_append, so it can be used to create normal .xz
# files. xzmisc uses smaller LZMA2 dictionary than xzkern, because a very
# big dictionary would increase the memory usage too much in the multi-call
# decompression mode. A BCJ filter isn't used either.
quiet_cmd_xzkern = XZKERN  $@
cmd_xzkern = (cat $(filter-out FORCE,$^) | \
	sh $(srctree)/scripts/xz_wrap.sh && \
	$(call size_append, $(filter-out FORCE,$^))) > $@ || \
	(rm -f $@ ; false)

quiet_cmd_xzmisc = XZMISC  $@
cmd_xzmisc = (cat $(filter-out FORCE,$^) | \
	xz --check=crc32 --lzma2=dict=1MiB) > $@ || \
	(rm -f $@ ; false)

# ASM offsets
# ---------------------------------------------------------------------------

# Default sed regexp - multiline due to syntax constraints
#
# Use [:space:] because LLVM's integrated assembler inserts <tab> around
# the .ascii directive whereas GCC keeps the <space> as-is.
define sed-offsets
	's:^[[:space:]]*\.ascii[[:space:]]*"\(.*\)".*:\1:; \
	/^->/{s:->#\(.*\):/* \1 */:; \
	s:^->\([^ ]*\) [\$$#]*\([^ ]*\) \(.*\):#define \1 \2 /* \3 */:; \
	s:->::; p;}'
endef

# Use filechk to avoid rebuilds when a header changes, but the resulting file
# does not
define filechk_offsets
	(set -e; \
	 echo "#ifndef $2"; \
	 echo "#define $2"; \
	 echo "/*"; \
	 echo " * DO NOT MODIFY."; \
	 echo " *"; \
	 echo " * This file was generated by Kbuild"; \
	 echo " */"; \
	 echo ""; \
	 sed -ne $(sed-offsets) < $<; \
	 echo ""; \
	 echo "#endif" )
endef
